<template>
  <el-alert
    v-if="isMobileVal"
    :title="mobileAlert"
    type="warning"
    center
    show-icon
    style="margin: 50px auto"
    :closable="false"
  />
  <div class="gantt-container" v-show="!isMobileVal&&hasEntity" v-title="ganttTitle">
    <div class="tips-desc">
      <span class="progress-status-point todo"></span>{{ todo }}
      <span class="progress-status-point doing"></span>{{ doing }}
      <span class="progress-status-point done"></span>计划完成
      <span class="progress-status-point process"></span>实际完成
      <span class="progress-status-point over"></span>{{ delay }}
      
    </div>
    <el-button
      v-if="!isMobileVal && canShareRef"
      :icon="Share"
      :loading="isSharingRef"
      class="share-btn"
      @click="share"
      size="small"
      >{{ shareBtn }}</el-button
    >
    <div ref="ganttRef" class="gantt" id="gantt"></div>
  </div>
  <div v-if="!isMobileVal&&!hasEntity" class="no-data">暂无甘特图数据</div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { fetchData, insertShareInfo, fetchShareInfo } from '@/api/qygly'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { gantt } from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import { reqAllPlan } from '@/api/config/plan'
import { isMobile } from '@/utils/common.js'
import { Share } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user.js'
import { usePltI18nStore } from '@/stores/i18n-plt'
// 导入甘特图配置工具
import { riskGanttColor, renderGantt } from './index.js'

// 状态管理与国际化
const store = useUserStore()
const pltI18nStore = usePltI18nStore()
const { shareBtn, todo, doing, done, delay } = pltI18nStore.pltI18n.cisdi.gczx.frontEnd.common
const { actualProgress, ganttTitle, mobileAlert } = pltI18nStore.pltI18n.cisdi.gczx.frontEnd.gantt

// 基础变量
let canShareRef = ref(false)
let isSharingRef = ref(false)
const isMobileVal = ref(false)
const route = useRoute()
const ganttRef = ref()
const req = ref({})
const tasks = reactive({ data: [] })
const hasEntity = ref(true) // 是否有数据
const { VITE_DOMAIN_LOCATION } = import.meta.env

/**
 * 获取甘特图数据（常规模式）
 */
const getData = async () => {
  tasks.data = []
  try {
    const res = await fetchData(req.value)
    const { entityRecordList } = res
    if (!entityRecordList || entityRecordList.length === 0) {
      hasEntity.value = false
      return
    }

    hasEntity.value = true
    // 格式化任务数据（适配双进度条需求）
    entityRecordList.forEach(item => {
      const { ID, NAME, PLAN_FR, PLAN_DAYS, ACT_FR, ACT_TO, ACT_DAYS } = item.textMap
      const parentId = item.valueMap.CC_PRJ_STRUCT_NODE_PID
      const findParent = entityRecordList.find(record => record.valueMap.ID === parentId)
      const status = item.valueMap.CC_WBS_PROGRESS_STATUS_ID
      const progress = item.valueMap.ACT_WBS_PCT ? item.valueMap.ACT_WBS_PCT / 100 : 0

      tasks.data.push({
        id: ID,
        text: NAME,
        start_date: PLAN_FR, // 计划开始时间
        duration: PLAN_DAYS, // 计划时长
        sj_start_date: ACT_FR, // 实际开始时间
        sj_end_date: ACT_TO, // 实际结束时间
        sj_duration: ACT_DAYS, // 实际时长
        status: status, // 任务状态（TODO/DOING/DONE/OVER）
        progress: progress, // 进度百分比（0-1）
        remark:item.textMap.REMARK ?item.textMap.REMARK :'',
        isCrux: item.textMap.IS_CRITICAL_PATH, // 是否关键路径
        parent: parentId && parentId !== ID && findParent ? parentId : null, // 父任务ID
        open: true // 默认展开
      })
    })

    renderGantt(ganttRef.value, tasks)
  } catch (err) {
    ElMessage.error('甘特图数据获取失败')
    console.error('getData error:', err)
  }
}

/**
 * 分享功能
 */
const share = () => {
  isSharingRef.value = true
  const orgId = store.loginInfo.currentOrgInfo?.id
  if (!orgId) {
    ElMessage.warning('无法获取当前组织ID，分享失败')
    isSharingRef.value = false
    return
  }

  insertShareInfo({
    shareUrl: `${VITE_DOMAIN_LOCATION}/#/ganttGy?orgId=${orgId}&shareId=@SHARE_ID`,
    shareContextData: JSON.stringify({ tasks: tasks })
  })
    .then(result => {
      const data = {
        mark: 'QYGLY',
        iframeId: route.query.iframeId,
        isReqOrResp: true,
        type: 'CONFIG_SHARE',
        commId: 'CONFIG_SHARE',
        content: { shareInfo: result }
      }
      window.parent.postMessage(data, '*')
      ElMessage.success('分享配置已发送')
    })
    .catch(err => {
      ElMessage.error('分享失败')
      console.error('share error:', err)
    })
    .finally(() => {
      isSharingRef.value = false
    })
}

/**
 * 生命周期：挂载后初始化
 */
onMounted(() => {
  isMobileVal.value = isMobile()

  // 1. 共享模式（通过shareId访问）
  if (route.query.shareId) {
    fetchShareInfo({
      orgId: route.query.orgId,
      id: route.query.shareId
    })
      .then(result => {
        const shareData = JSON.parse(result.shareContextData)
        if (shareData?.tasks?.data) {
          renderGantt(ganttRef.value, shareData.tasks)
        } else {
          hasEntity.value = false
          ElMessage.warning('共享数据格式异常')
        }
      })
      .catch(err => {
        ElMessage.error('共享数据获取失败')
        console.error('fetchShareInfo error:', err)
      })
    return
  }

  // 2. 常规模式（需选择项目）
  if (!store.loginInfo?.globalVarMap?.P_CC_PRJ_IDS) {
    ElMessage({
      showClose: true,
      message: '当前没选择项目，请选择项目',
      type: 'warning',
      duration: 0,
      offset: 150
    })
    hasEntity.value = false
    return
  }

  // 初始化请求参数
  req.value = {
    ...reqAllPlan,
    sevId: route.query.sevId // 区分现行/历史计划
  }

  // 开发环境直接拉取数据
  if (import.meta.env.MODE === 'development') {
    getData()
  }

  // 向父窗口发送就绪信号
  const iframeId = route.query.iframeId
  if (iframeId) {
    window.parent.postMessage({
      mark: 'QYGLY',
      iframeId: iframeId,
      isReqOrResp: true,
      type: 'READY_TO_FETCH',
      commId: 'READY_TO_FETCH'
    }, '*')
  }

  canShareRef.value = true
})

/**
 * 监听父窗口消息（接收企业云数据）
 */
window.addEventListener('message', async (e) => {
  if (e.data?.mark !== 'QYGLY') return

  // 更新请求参数
  req.value = {
    ...reqAllPlan,
    ...e.data.content, // 企业云postmessage发过来的数据
    sevId: route.query.sevId // 保留路由中的计划类型
  }
  
  console.info('cisdi-gantt收到的message', e.data.content)
  getData()
}, false)
</script>

<style lang="scss">
$todo-color: #606266;
$done-color: #2daa98;
$doing-color: #ff9500;
$over-color: #ff4949;
// $process-color: #299cb4;
$process-color: #005AA6;

.gantt-container {
  height: 100vh;
  padding-top: 50px;

  .share-btn {
    position: fixed;
    right: 10px;
    top: 10px;
    z-index: 99;
  }

  .tips-desc {
    position: fixed;
    left: 10px;
    top: 10px;
    z-index: 99;
    font-size: 14px;
    color: #5c5c5c;
    display: flex;
    align-items: center;
    gap: 8px;

    .progress-status-point {
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 2px;

      &.todo {
        background-color: $todo-color;
      }

      &.doing {
        background-color: $doing-color;
      }

      &.done {
        background-color: $done-color;
      }
      &.over {
        background-color: $over-color;
      }
      &.process {
        background-color: $process-color;
      }
    }
  }
}

.gantt {
  height: calc(100vh - 60px);
  
  .gantt_task_line {
    background-color: #fdf6f6 !important;
    border: none !important;
    min-width: 11px;
  }
  
  .todo {
    background-color: #dbdbdb;
    border: none;
    .gantt_task_content {
      color: rgb(96, 98, 102);
    }
  }
  
  .doing {
    background-color: #fcf4eb;
    border: none;
    .gantt_task_content {
      color: #ff9500;
    }
  }
  
  .done {
    background-color: #e4f9ed;
    border: none;
    .gantt_task_content {
      color: #2daa98;
    }
    .gantt_task_progress {
      background-color: #e4f9ed;
    }
  }
  
  .over {
    background-color: #fce6e6;
    border: none;
    .gantt_task_content {
      color: #ff4949;
    }
  }
}

.no-data {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
}
</style>
